//
//  XYOriginateView.swift
//  SinaWB_XY
//
//  Created by 小熊猫 on 15/10/20.
//  Copyright © 2015年 小熊猫. All rights reserved.
//

import UIKit

//最大图片数
private let IMAGE_MAX_NUM:CGFloat = 9

//图片之间的间距
private let IMAGE_MAGIN:CGFloat = 10


class XYOriginateView: UIView {
    
    //储存图片的数组
    var pic_urls:[XYPicModel]?{
        didSet{
            setImagePic()
        }
    }
    

    override init(frame: CGRect) {
        super.init(frame: frame)
        
        //初始化就添加9个图片
        for _ in 0..<Int(IMAGE_MAX_NUM){
            
            let imageView = XYOriginateImageView(frame:CGRectZero)
            
            addSubview(imageView)
        }

    }
    
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //显示图片
    private func setImagePic(){
        //遍历view中的控件
        for view in subviews{
            view.hidden = true
            //把所有子控件隐藏起来
        }
        
        //遍历数组,看传进来多少图片
        for i in 0..<pic_urls!.count{
            let imageView = subviews[i] as! XYOriginateImageView
            imageView.hidden = false
            
            let picView = pic_urls![i]
            
            //把模型中的图片给自定义
            imageView.thumbnail_pic = picView.thumbnail_pic
        }
    }

    //计算view的高度
    class func size(count:Int) -> CGSize{
        //一行最大得图片数
        let maxCol = 3
        
        //计算有多少行
        let row = (count - 1) / maxCol + 1
        //计算图片宽高
        let imageWidth = (SCREENW - 4 * IMAGE_MAGIN) / CGFloat(maxCol)
        
        let imageH = CGFloat(row) * imageWidth + CGFloat(row - 1) * IMAGE_MAGIN
        let imageW = SCREENW - 2 * IMAGE_MAGIN
        return CGSizeMake(imageW, imageH)
        
    }
    
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        if pic_urls == nil {return}
        
        let maxCol = 3
        
        let imageWidth = (SCREENW - 4 * IMAGE_MAGIN) / CGFloat(maxCol)
        
        let count = pic_urls!.count == 4 ? 2 : maxCol
        
        //把配图View中的图片遍历
        for i in 0..<pic_urls!.count{
            let image = subviews[i]
            
            
            //计算有多少行
            let row = i / count
            let col = i % count
            
            let imageX = CGFloat(col) * (imageWidth + IMAGE_MAGIN)
            let imageY = CGFloat(row) * (imageWidth + IMAGE_MAGIN)
            
            image.frame = CGRectMake(imageX, imageY, imageWidth, imageWidth)
        }
        
    }
    
}





